let express = require('express');
let router = express.Router();
let mongoose = require('mongoose');
let Goods = require('../models/goods');

//连接mongoDB数据库
mongoose.connect('mongodb://127.0.0.1:27017/db_demo');
mongoose.connection.on("connected",function(){
  console.log("MongoDB connected success!")
});

mongoose.connection.on("error",function(){
  console.log("MongoDB connected fail!")
});
mongoose.connection.on("disconnected",function(){
  console.log("MongoDB connected disconnected!")
});
//查询商品列表数据
router.get("/list",function(req,res,next){
  let page = parseInt(req.param("page"));  //拿一个分页，里面的参数是当前页
  let pageSize = parseInt(req.param("pageSize"));
  //价格帅选参数
  let priceLevel = req.param("priceLevel");
  let skip = (page-1)*pageSize;
  let priceGt= "";   //价格最小区间
  let priceLte="";  //价格最大区间
  let params ={};
  if(priceLevel!='all'){
    switch(priceLevel){
      case '0':priceGt=0;priceLte=100;break;
      case '1':priceGt=100;priceLte=500;break;
      case '2':priceGt=500;priceLte=1000;break;
      case '3':priceGt=1000;priceLte=5000;break;
    }
    params ={
      salePrice:{
        $gt:priceGt,
        $lte:priceLte
      }
    }
  }

  //实现分页
  //实现排序功能
  let sort = req.param("sort");  //定义一个变量，这个是前端传过来的,跳过几条数据，limit显示几条数据
  let goodModel = Goods.find(params).skip(skip).limit(pageSize);
  goodModel.sort({'salePrice':sort});
  goodModel.exec(function(err,doc){
   if(err){
     res.json({
       status:'1',
       msg:err.message
     });
   }else{
     res.json({
       status:'0',
       msg:'',
       result:{
         count:doc.length, //总条数
         list:doc
       }
     })
   }
 })
});

//提交到购物车
router.post("/addCart",function(req,res,next){
  //假设已经登陆
  let userId = '100000077';
  //注意，post提交，数据在报文中，通过body获取
  let productId = req.body.productId;
  let User = require('../models/user');
  User.findOne({userId:userId},function(err,userDoc){
    if(err){
      res.json({
        status:"1",
        msg:err.message
      })
    }else{
      console.log("userDoc:"+userDoc);
      if(userDoc){
        //实现数据的计数，就是有就加1，没有就给值为1
        let goodsItem ='';  //定义新增的变量
        userDoc.cartList.forEach(function(item){
          if(item.productId == productId){
            goodsItem = item;
            item.productNum ++;
          }
        });
        if(goodsItem){
          userDoc.save(function(err2, doc2) {
            if (err2) {
              res.json({
                status: "1",
                msg: err2.message
              })
            } else {
              res.json({
                status: '0',
                msg: '',
                result: 'suc'
              })
            }
          })
        }else {
          Goods.findOne({productId: productId}, function (err1, doc) {
            if (err1) {
              res.json({
                status: "1",
                msg: err1.message
              })
            } else {
              if (doc) {
                doc.productNum = 1;
                doc.checked = 1; //加入购物车时默认选中
                userDoc.cartList.push(doc);
                userDoc.save(function(err2, doc2){
                  if (err2) {
                    res.json({
                      status: "1",
                      msg: err2.message
                    })
                  } else {
                    res.json({
                      status: '0',
                      msg: '',
                      result: 'suc'
                    })
                  }
                })
              }
            }
          })
        }
      }
    }
  })
});

module.exports = router;
